package cn.com.xxlibrary.action;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.ExceptionMapping;
import org.apache.struts2.convention.annotation.ExceptionMappings;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.stereotype.Controller;

import cn.com.xxlibrary.util.AuthCode;
import cn.com.xxlibrary.util.AuthImage;
import cn.com.xxlibrary.util.UtilTools;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Controller
@Namespace(value = "/")
@ParentPackage("struts-default")
@ExceptionMappings({ @ExceptionMapping(exception = "java.lang.Exception", result = "error") })
public class AuthCodeAction extends ActionSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	// 图片流
	private ByteArrayInputStream imageStream;

	String authCode;

	/**
	 * 生成验证码图片
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action(value = "AuthImg", results = { @Result(name = SUCCESS, type = "stream", params = {
			"contentType", "image/jpeg", "inputName", "imageStream",
			"bufferSize", "2048" }) })
	public String AuthImg() throws Exception {
		// 如果开启Hard模式，可以不区分大小写
		// String securityCode = AuthCode.getSecurityCode(4,AuthCodeLevel.Hard,
		// false).toLowerCase();

		// 获取默认难度和长度的验证码
		String securityCode = AuthCode.getSecurityCode();
		imageStream = AuthImage.getImageAsInputStream(securityCode);

		// 放入session中
		ActionContext.getContext().getSession()
				.put("SESSION_SECURITY_CODE", securityCode);
		return SUCCESS;
	}

	/**
	 * 验证验证码
	 * 
	 * @throws IOException
	 */
	@Action(value = "verifyCode")
	public void verifyCode() throws IOException {
		String securityCode = ActionContext.getContext().getSession()
				.get("SESSION_SECURITY_CODE").toString().toLowerCase();
		if (authCode != "" && authCode.toLowerCase().equals(securityCode)) {
			UtilTools.sendMsg(SUCCESS);
		} else {
			UtilTools.sendMsg(ERROR);
		}
	}

	// ========================================

	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}

	public String getAuthCode() {
		return authCode;
	}

	public void setAuthCode(String authCode) {
		this.authCode = authCode;
	}
}
